# 运用操作系统提供的锁机制，如 multiprocessing.Lock，在执行日志文件轮转操作时加锁，保证同一时刻仅有一个进程能进行相关操作。
# 上述代码通过 log_lock 锁，确保日志文件轮转操作的原子性，避免多进程竞争引发异常。

from fastapi import FastAPI
from logging.handlers import TimedRotatingFileHandler

import multiprocessing
import logging


app = FastAPI()


# log_queue = multiprocessing.Queue()
log_lock = multiprocessing.Lock()


def setup_logging():
    formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
    file_handler = TimedRotatingFileHandler('app.log', when='midnight')
    file_handler.setFormatter(formatter)
    logger = logging.getLogger('app')
    logger.addHandler(file_handler)
    logger.setLevel(logging.INFO)
    return logger


def roate_log_file(logger):
    with log_lock:
        for handler in logger.handlers:
            if isinstance(handler, TimedRotatingFileHandler):
                handler.doRollover()


@app.get("/")
def read_root():
    logger = setup_logging()
    logger.info("Handling root request")
    # 假设这里需要手动触发轮转
    return {"Hello": "World"}


if __name__=="__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000)